package com.freewater.parking.infrastructure.query;

import com.freewater.parking.infrastructure.db.DailyRevenueDao;
import com.freewater.parking.infrastructure.db.DailyRevenueTable;
import com.freewater.parking.domain.common.DomainEventListener;
import com.freewater.parking.domain.common.DomainEvent;
import com.freewater.parking.domain.parking.PaidEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Optional;

@Component
@Transactional
public class DailyRevenueMaterializer implements DomainEventListener {

    private final DailyRevenueDao dailyRevenueDao;

    public DailyRevenueMaterializer(DailyRevenueDao dailyRevenueDao) {
        this.dailyRevenueDao = dailyRevenueDao;
    }

    @Override
    public void onEvent(DomainEvent event) {
        if (event instanceof PaidEvent paidEvent) {
            this.updateOnPaidEvent(paidEvent);
        }
    }

    private void updateOnPaidEvent(PaidEvent paidEvent) {
        LocalDate day = paidEvent.getPayTime().toLocalDate();
        Optional<DailyRevenueTable> revenueTable = this.dailyRevenueDao.findById(day);
        if (revenueTable.isPresent()) {
            this.dailyRevenueDao.updateRevenue(day, paidEvent.getAmount());
        } else {
            DailyRevenueTable dailyRevenueTable = new DailyRevenueTable();
            dailyRevenueTable.setId(day);
            dailyRevenueTable.setRevenue(paidEvent.getAmount());
            this.dailyRevenueDao.save(dailyRevenueTable);
        }
    }
}
